// pages/killPrice/orderPay.js
var app = getApp();
var utils = require('../../utils/util.js');
Page({
  data: {
    items: [{
        name: '选择自提',
        value: '1'
      },
      {
        name: '送货上门',
        value: '2'
      },
      {
        name: '产地直发',
        value: '3',
        checked: 'true'
      },
    ],
    multiArray: [
      ['今天', '明天', '后天'],
      ['08:00-10:00', '10:00-12:00', '12:00-14:00', '14:00-16:00', '16:00-18:00']
    ],
    multiIndex: [0, 0],
    valuetab: 2,
    currentTab: 0,
    currentBut: 0,
    currentBut1: 0,
    isHide: true, //支付弹窗是否显示
    coupon: 0,
    typePay: "wx_pay",
    storeId: "", //店铺id  不必须传，只是在自提的时候传输，需在最近的3家店铺获取id
    addressId: "", //地址id  不必须传 需在 我的 我的地址列表中获取id
    couponId: "", //优惠券id  不必须传 需在 、
    deliveryTime: "",
    buttonClicked: false,
    isphone: false,
    freight: 0
  },
  //获取订单信息
  bargain_order_details: function(order_id = '', callback = '') {
    var that = this;
    utils.showLoading();
    var url = '/api/v1/bargaingoods/bargain_order';
    var param = {
      order_id: order_id
    };
    utils.http(url, param, function(res) {
      utils.hideLoading();
      if (!res.datas) return false;
      that.setData({
        order_id: res.datas.id,
        bargain_order: res.datas
      }, function() {
        that.setData({
          goodsOrder: [{
            goods_id: that.data.bargain_order.spec_id,
            num: 1
          }],
          type: wx.getStorageSync("type"),
        })
        typeof callback == 'function' ? callback() : ''
      })
    })
  },
  onLoad: function(options) {
    var that = this;
    that.setData({
      order_id: options.order_id
    }, function() {
      that.getStorageLocation();
    });
  },
  //获取位置信息?
  getStorageLocation: function() {
    var that = this;
    wx.getStorage({
      key: 'userLocation',
      success: function(res) {
        var split = res.data.split(",");
        that.setData({
          latitude: split[0],
          longitude: split[1]
        })
      },
    })
  },
  //页面展示时，商品信息
  onShow: function() {
    var that = this;
    //用户信息
    that.personalInfo();
    //获取砍价的订单信息
    that.bargain_order_details(that.data.order_id, function() {
      //获取收货地址
      that.addressInfo();
      //优惠券更新
      that.getNewCoupon();
      //查运费
      that.get_freight();
    });
  },
  //页面展示时重新获取优惠券信息
  getNewCoupon: function() {
    var that = this;
    if (app.globalData.couponId != undefined) {
      that.setData({
        couponId: app.globalData.couponId
      })
    }
    if (app.globalData.couponMoney != undefined) {
      that.setData({
        money: app.globalData.couponMoney,
        coupon: "-" + app.globalData.couponMoney
      })
    } else {
      that.mycouponTap();
    }
  },
  addressInfo: function() {
    var that = this;
    console.log('globalData 中的地址id', app.globalData.addressChid);
    if (app.globalData.addressChid != undefined) {
      utils.http("/api/v1/address/address_info", {
        id: app.globalData.addressChid
      }, function(res) {
        app.globalData.addressChid = undefined;
        that.setData({
          defaultAddress: res.datas,
          addressId: res.datas.id
        })
      })
    } else {
      utils.http("/api/v1/address/address_info", {}, function(res) {
        console.log(res);
        if (res.datas != null) {
          that.setData({
            defaultAddress: res.datas,
            addressId: res.datas.id
          })
        }

      })
    }
  },
  //我的个人信息
  personalInfo: function(e) {
    var that = this;
    utils.showLoading();
    utils.http("/api/v1/member/index", {}, function(res) {
      utils.hideLoading();
      that.setData({
        info: res.datas,
      });
    })
  },
  //计算总价
  getTotalPrice: function() {
    var that = this;
    var totalPrice = 0;
    var bargain_order = that.data.bargain_order;
    totalPrice = (parseFloat(bargain_order.total_price)) + that.data.freight
    totalPrice = totalPrice.toFixed(2);
    totalPrice = that.data.money != undefined ? (totalPrice - that.data.money) : totalPrice;
    that.setData({
      totalPrice: totalPrice,
      oktotalPrice: totalPrice
    }, function() {

    })
  },
  // 获取我的优惠券可使用数据 
  mycouponTap: function() {
    var that = this;
    utils.http("/api/v1/order/my_coupon", {
      goods_list: that.data.goodsOrder
    }, function(res) {
      that.setData({
        coupon: "可用 (" + res.datas.use_total + "张优惠卷)"
      })
    })
  },
  //获取运费
  get_freight: function() {
    var that = this;
    utils.http("/api/v1/order/get_freight", {
      goods_list: that.data.goodsOrder
    }, function(res) {
      that.setData({
        freight: res.datas
      }, function() {
        that.getTotalPrice()
      })
    })
  },
  //选择自提、送货上门列表
  nearbyStoreList: function(latitude, longitudeq, goodsList) {
    var that = this;
    utils.http("/api/v1/order/nearby_store", {
      latitude: latitude,
      longitude: longitudeq,
      goods_list: goodsList
    }, function(res) {
      that.setData({
        storeList: res.datas,
        storeId: res.datas[0].id
      })
    })
  },
  //订单单选项
  radioChange(e) {
    var that = this;
    this.setData({
      valuetab: e.detail.value
    })
    that.nearbyStoreList(that.data.latitude, that.data.longitude, that.data.goodsOrder);
    if (e.detail.value == 0) {
      console.log(that.data.info.phone)
      if (that.data.info.phone == "") {
        that.setData({
          isphone: true
        })
      }
      that.setData({
        addressId: "",
      })
    }
    if (e.detail.value == 1) {
      that.setData({
        addressId: that.data.addressId,
        isphone: false
      })
    }
    if (e.detail.value == 2) {
      that.setData({
        addressId: that.data.addressId,
        isphone: false
      })
    }
  },
  //选择自提
  bindMultiPickerChange(e) {
    console.log(e);
    var that = this;
    var arr = e.detail.value;
    var one = that.data.multiArray[0][arr[0]];
    var two = that.data.multiArray[1][arr[1]];
    this.setData({
      multiIndex: e.detail.value,
      deliveryTime: one + "" + two
    })
  },

  //店铺单项选择 （送货上门）
  bindSvTap: function(e) {
    var id = e.currentTarget.dataset.current;
    this.setData({
      currentTab: id
    })
  },
  //店铺单项选择 （选择自提）
  bindButTap: function(e) {
    var that = this;
    var index = e.currentTarget.dataset.current;
    this.setData({
      currentBut1: index,
      storeId: that.data.storeList[index].id,
    })
  },
  //优惠券
  onCouponTap: function(e) {
    console.log(1)
    wx.navigateTo({
      url: '../coupon/coupon',
    })
  },
  //关闭支付弹窗
  onColseTap: function(e) {
    this.setData({
      isHide: true
    })
  },
  // getPhoneNumber  手机号授权
  getPhoneNumber: function(e) {
    var that = this;
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      // 登录
      wx.login({
        success: res => {
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          utils.http("/api/v1/common/get_wechat_phone", {
            js_code: res.code,
            iv: e.detail.iv,
            encryptedData: e.detail.encryptedData
          }, function(res) {
            if (res.state == 1) {
              that.phoneDiel(res.datas)
              that.setData({
                isphone: false
              })
              wx.showModal({
                title: '',
                showCancel: false,
                confirmText: "授权成功",
                content: '您已授权手机号成功',
                success: function(res) {
                  if (res.confirm) {
                    that.setData({
                      isHide: false
                    })
                  }

                }
              })

            }
          })
        }
      })
    }


  },
  phoneDiel: function(phone) {
    var that = this;
    utils.http("/api/v1/member/member_modify", {
      phone: phone
    }, function(res) {
      if (res.datas == 1) {
        this.personalInfo();
      }
    })
  },
  //打开支付弹窗
  onOrderTap: function(e) {
    var that = this;
    if (!that.data.addressId) {
      wx.showToast({
        title: '请填写地址~',
        icon: 'none'
      });
      return false;
    }
    if (that.data.valuetab == 1) {
      // 检测时间
      var myDate = new Date();
      var nowH = myDate.getHours();
      var multiIndex = that.data.multiIndex; //获取当前小时数(0-23)
      if (nowH >= 10 && multiIndex[0] == 0 && multiIndex[1] == 0) {
        wx.showToast({
          title: '请重新选择正确的配送时间',
          icon: "none"
        })
        return false;
      }
      if (nowH >= 12 && multiIndex[0] == 0 && multiIndex[1] <= 1) {
        wx.showToast({
          title: '请重新选择正确的配送时间',
          icon: "none"
        })
        return false;
      }
      if (nowH >= 14 && multiIndex[0] == 0 && multiIndex[1] <= 2) {
        wx.showToast({
          title: '请重新选择正确的配送时间',
          icon: "none"
        })
        return false;
      }
      if (nowH >= 16 && multiIndex[0] == 0 && multiIndex[1] <= 3) {
        wx.showToast({
          title: '请重新选择正确的配送时间',
          icon: "none"
        })
        return false;
      }

      if (nowH >= 18 && multiIndex[0] == 0 && multiIndex[1] <= 4) {
        wx.showToast({
          title: '请重新选择正确的配送时间',
          icon: "none"
        })
        return false;
      }
    }
    this.setData({
      isHide: false
    })
  },
  //支付方式
  paymentTypeTap: function(e) {
    var id = e.currentTarget.dataset.id;
    var currentBut = id;
    this.setData({
      currentBut: currentBut,
      typePay: e.currentTarget.dataset.type,
      buttonClicked: false
    })
  },
  //立即支付
  onOrderSuccessTap: function(e) {
    var that = this;
    if (that.data.buttonClicked == false) {
      utils.showLoading();
      that.setData({
        buttonClicked: true
      })
      var param = {
        order_id: that.data.order_id,
        payment_code: that.data.typePay,
        get_type: that.data.valuetab,
        store_id: that.data.storeId,
        address_id: that.data.addressId,
      };
      utils.http("/api/v1/bargaingoods/add_order", param, function(res) {
        utils.hideLoading();
        if (res.state == 1) {
          if (that.data.typePay == "wx_pay") {
            wx.requestPayment({
              timeStamp: res.datas.timeStamp,
              nonceStr: res.datas.nonceStr,
              package: res.datas.package,
              signType: res.datas.signType,
              paySign: res.datas.paySign,
              success() {
                that.paySuccessCallback(res);
              },
              fail(res) {
                that.setData({
                  buttonClicked: false
                })
              }
            })
          } else {
            that.paySuccessCallback(res);
          }
        } else if (res.state == 10001) {
          that.paySuccessCallback(res);
        } else {
          utils.message(res.datas);
          that.setData({
            buttonClicked: false
          })
        }
      })
    }
  },
  paySuccessCallback: function(res) {
    app.globalData.couponMoney = undefined;
    app.globalData.couponId = undefined;
    wx.redirectTo({
      url: '../ordersuccess/ordersuccess?orderid=' + res.datas.order_id + "&totalprice=" + res.datas.total_price
    })
  },
  //跳入我的地址页面
  onMyAddressTap: function(e) {
    app.globalData.typeaddress = 0
    wx.navigateTo({
      url: '../personal/myaddress/myaddress?typeaddress=' + app.globalData.typeaddress,
    })
  },
})